<template>
	<!-- 附近的设备 -->
	<view class="p-40">
		<view class="u-flex u-row-between">
			<view class="f-blod">可用设备</view>
			<image src="../../static/refresh.png" class="refresh-icon" :class="_discoveryStarted?'roate-self':''"></image>
		</view>
		<view class="item-box" v-for="(item,index) in devices" @click="createBLEConnection(item.deviceId)">
			<image style="width: 40rpx;" mode="widthFix" src="../../static/bluetooth.png"></image>
			<view class="u-flex-1 m-l-20 font-16">{{item.name || item.localName || item.deviceId}}</view>
			<image src="../../static/arrow-right.png" style="width: 35rpx;" mode="widthFix"></image>
		</view>
	</view>
</template>

<script>
	import {
		getUuid,
		writeBLECharacteristicValue,
		CODE_MESSAGE
	} from "../../utils/common";
	import {
		getUser,
		getDevice,
		setDevice,
		setLastConnectedDevice
	} from "../../utils/storage";


	function inArray(arr, key, val) {
		for (let i = 0; i < arr.length; i++) {
			if (arr[i][key] === val) {
				return i;
			}
		}
		return -1;
	}
	// ArrayBuffer转16进度字符串示例
	function ab2hex(buffer) {
		var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
			return ("00" + bit.toString(16)).slice(-2);
		});
		return hexArr.join("");
	}
	export default {
		data() {
			return {
				title: "附近的设备",
				devices: [],
				connected: false,
				bufferValue: "",
				deviceId: "",
				serviceId: "",
				characteristicId: "",
				_discoveryStarted: false,
				app: "",
			};
		},
		onLoad() {
			// this.openBluetoothAdapter();
			this.app = getApp();
		},
		onShow() {
			this.openBluetoothAdapter();
		},
		onHide() {
			console.log("onHide");
			if(this._discoveryStarted){
				this.stopBluetoothDevicesDiscovery();
			}
		},
		onUnload() {
			console.log("onUnload");
			if(this._discoveryStarted){
				this.stopBluetoothDevicesDiscovery();
			}
		},
		methods: {
			openBluetoothAdapter() {
				console.log("openBluetoothAdapter");
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log("openBluetoothAdapter success", res);
						this.startBluetoothDevicesDiscovery();
					},
					fail: (res) => {
						console.log("openBluetoothAdapter fail", res);
						if (res.errCode === 10001) {
							uni.showModal({
								title: "连接不成功",
								content: `请确定手机蓝牙已打开`,
								showCancel: false,
								confirmText: "好",
								success() {},
							});
							uni.onBluetoothAdapterStateChange((res) => {
								console.log("onBluetoothAdapterStateChange", res);
								if (res.available) {
									// 取消监听，否则stopBluetoothDevicesDiscovery后仍会继续触发onBluetoothAdapterStateChange，
									// 导致再次调用startBluetoothDevicesDiscovery
									uni.onBluetoothAdapterStateChange(() => {});
									this.startBluetoothDevicesDiscovery();
								}
							});
						}
					},
				});
			},
			startBluetoothDevicesDiscovery() {
				if (this._discoveryStarted) {
					return;
				}
				this._discoveryStarted = true;
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey:true,
					success: (res) => {
						console.log("startBluetoothDevicesDiscovery success", res);
						this.onBluetoothDeviceFound();
					},
					fail: (res) => {
						console.log("startBluetoothDevicesDiscovery fail", res);
					},
				});
			},
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					complete: () => {
						console.log("stopBluetoothDevicesDiscovery", this.devices);
						this._discoveryStarted = false;
					},
				});
			},
			onBluetoothDeviceFound() {
				uni.onBluetoothDeviceFound((res) => {
					res.devices.forEach((device) => {
						console.log("发现的蓝牙设备", device);
						console.log("发现的蓝牙设备名称",device.localName, device.name);
						const deviceList = getDevice();
						const deviceIds = deviceList.map((item) => item.deviceId);
						if (deviceIds.includes(device.deviceId)) {
							return;
						}
						if (!device.name && !device.localName) {
							return;
						}
						const foundDevices = this.devices;
						const idx = inArray(foundDevices, "deviceId", device.deviceId);
						if (idx === -1) {
							this.devices.push(device);
						} else {
							this.devices.splice(idx, 1, device);
						}
					});
				});
			},
			createBLEConnection(deviceId) {
				const selectedDevice = this.devices.find((item) => item.deviceId === deviceId);
				const name = selectedDevice.name || selectedDevice.localName;
				this._createBLEConnection(deviceId, name);
			},
			_createBLEConnection(deviceId, name) {
				const _this = this;
				uni.showLoading({
					title: "连接中...",
				});
				uni.createBLEConnection({
					deviceId,
					success: () => {
						console.log("createBLEConnection success");
						uni.hideLoading();
						_this.app.globalData.deviceId = deviceId;
						const deviceList = getDevice();
						const deviceData = {
							name,
							deviceId
						};
						deviceList.push(deviceData);
						setDevice(deviceList);
						setLastConnectedDevice(deviceData);
						this.connected = true;
						this.name = name;
						this.deviceId = deviceId;
						// this.checkUser();
						// this.getBLEDeviceServices(deviceId);
						this.stopBluetoothDevicesDiscovery();
						uni.showModal({
							title: "连接成功",
							content: `蓝牙设备“${name}”连接成功`,
							showCancel: false,
							confirmText: "好",
							success() {
								uni.redirectTo({
									url: "/pages/function-list/function-list"
								});
							},
						});
					},
					fail: (res) => {
						console.log("createBLEConnection fail", res);
						uni.hideLoading();
						this.deviceId = "";
						const errorMsg = CODE_MESSAGE[res.errCode];
						// const foundDevices = _this.data.devices;
						// const idx = inArray(foundDevices, "deviceId", deviceId);
						// if (idx !== -1) {
						//   foundDevices.splice(idx, 1);
						// }
						// console.log("_this.data.devices", _this.data.devices);
						// _this.setData({
						//   devices: _this.data.devices,
						// });
						uni.showModal({
							title: "连接不成功",
							content: `蓝牙设备“${name}”连接失败：${errorMsg}`,
							showCancel: false,
							confirmText: "好",
							success() {},
						});
					},
				});
			},
			closeBLEConnection() {
				uni.closeBLEConnection({
					deviceId: this.deviceId,
				});
				this.connected = false;
				this.canWrite = false;
				this.deviceId = "";
			},
			getBLEDeviceServices(deviceId) {
				uni.getBLEDeviceServices({
					deviceId,
					success: (res) => {
						console.log("getBLEDeviceServices", res);
						for (let i = 0; i < res.services.length; i++) {
							if (res.services[i].isPrimary) {
								this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
								return;
							}
						}
					},
				});
			},
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				uni.getBLEDeviceCharacteristics({
					deviceId,
					serviceId,
					success: (res) => {
						console.log("getBLEDeviceCharacteristics success", res.characteristics);
						// 这里会存在特征值是支持write，写入成功但是没有任何反应的情况
						// 只能一个个去试
						for (let i = 0; i < res.characteristics.length; i++) {
							const item = res.characteristics[i];
							if (item.properties.write) {
								this.canWrite = true;
								this.deviceId = deviceId;
								this.serviceId = serviceId;
								this.characteristicId = item.uuid;
								break;
							}
						}
					},
					fail(res) {
						console.error("getBLEDeviceCharacteristics", res);
					},
				});
			},
			checkUser() {
				const userInfo = getUser();
				const {
					openid
				} = userInfo;
				const serviceId = getUuid("5508");
				writeBLECharacteristicValue(serviceId, getUuid("0083"), openid);
			}
		}

	}
</script>

<style lang="scss" scoped>
	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}
		to {
			transform: rotate(360deg);
		}
	}

	.refresh-icon {
		width: 45rpx;
		height: 45rpx;
	}

	.roate-self{
		animation: rotate 3s linear infinite;
	}
	.item-box {
		background-color: white;
		margin-top: 30rpx;
		padding: 30rpx;
		display: flex;
		align-items: center;
		border-radius: 15rpx;
		box-shadow: 0px 3px 8px 0px rgba(0, 0, 0, 0.16);

	}
</style>